﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using SCGILite.NetLib;
using SCGILite.Helper;

namespace SCGITest.PageTemplate
{
    class TemplatePage : Panel
    {
        public DemoSCGISession se { get; set; }
        #region Title
        string _Title = "Page";
        public string Title
        {
            get
            {
                return _Title;
            }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                    _Title = "Page";
                else
                    _Title = value;
            } 
        }
        #endregion

        #region RenderHtml
        protected virtual void RenderHtml(HtmlTextWriter writer)
        {
            writer.WriteLine("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
            writer.WriteLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");            writer.WriteFullBeginTag("title");            writer.WriteEncodedText(this.Title);
            writer.WriteEndTag("title");
            writer.WriteLine("<body>");// style=\"width:100%\">");
            this.Render(writer);
            writer.WriteEndTag("body");
            writer.WriteEndTag("html");
        }
        #endregion

        #region RenderStream
        public static void RenderStream(TemplatePage page, Stream ms)
        {
            StreamWriter wr = new StreamWriter(ms, Encoding.UTF8);
            HtmlTextWriter write = new HtmlTextWriter(wr);
            page.RenderHtml(write);
            write.Flush();
        }
        #endregion

        protected virtual void ctorControl()
        {
        }

        public virtual void End()
        {
            MemoryStream ms = new MemoryStream();
            ctorControl();
            TemplatePage.RenderStream(this, ms);
            ms.Position = 0;
            se.ResponseHeaders(null, 200, (int)(ms.Length));
            se.SendResponse(new NetOutputStream(ms));
            se.EndResponse();
        }
    }
}
